package com.wei.wiki.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wei.wiki.mapper.EbookMapper;
import com.wei.wiki.pojo.Ebook;
import com.wei.wiki.pojo.EbookExample;
import com.wei.wiki.req.EbookQueryReq;
import com.wei.wiki.req.EbookSaveReq;
import com.wei.wiki.resp.EbookQueryResp;
import com.wei.wiki.resp.PageResp;
import com.wei.wiki.service.EbookService;
import com.wei.wiki.util.CopyUtil;
import com.wei.wiki.util.SnowFlake;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/*
 * @author : ShunWei
 * @date : 2022/1/27 20:54
 * @Description:
 */
@Service
public class EbookServiceImpl implements EbookService {
    private EbookMapper ebookMapper;

    @Autowired
    public void setEbookMapper(EbookMapper ebookMapper) {
        this.ebookMapper = ebookMapper;
    }

    @Resource
    private SnowFlake snowFlake;

    @Override
    public PageResp<EbookQueryResp> bookList(EbookQueryReq req) {
        EbookExample example = new EbookExample();
        EbookExample.Criteria criteria = example.createCriteria();
        if (!ObjectUtils.isEmpty(req.getName())) {
            criteria.andNameLike("%" + req.getName() + "%");
        }
        if (!ObjectUtils.isEmpty(req.getCategory2Id())) {
            criteria.andCategory2IdEqualTo(req.getCategory2Id());
        }
        criteria.andStatusEqualTo(true);
        PageHelper.startPage(req.getPage(), req.getSize());
        List<Ebook> ebookList = ebookMapper.selectByExample(example);
        PageInfo<Ebook> pageInfo = new PageInfo<>(ebookList);

        List<EbookQueryResp> list = CopyUtil.copyList(ebookList, EbookQueryResp.class);
        PageResp<EbookQueryResp> pageResp = new PageResp();
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setList(list);
        return pageResp;
    }

    @Override
    public void save(EbookSaveReq req) {
        Ebook ebook = CopyUtil.copy(req, Ebook.class);
        if (ObjectUtils.isEmpty(ebook.getId())) {
            // 新增
            ebook.setId(snowFlake.nextId());
            ebook.setCreateTime(new Date());
            ebook.setViewCount(0);
            ebook.setVoteCount(0);
            ebook.setStatus(true);
            ebookMapper.insertSelective(ebook);
        } else {
            // 更新
            ebook.setUpdateTime(new Date());
            ebookMapper.updateByPrimaryKeySelective(ebook);
        }
    }

    @Override
    public void delete(Long id) {
        ebookMapper.deleteByPrimaryKey(id);
    }
}
